import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:hitutor/Util/DateUtil.dart';
import 'package:hitutor/Util/Global.dart';
import 'package:hitutor/Util/MyColor.dart';
import 'package:hitutor/Util/PageUtil.dart';
import 'package:hitutor/Widget/MyBgPage.dart';
import 'package:hitutor/Widget/MyButton.dart';
import 'package:hitutor/Widget/MyDialog.dart';
import 'package:hitutor/Widget/MyImage.dart';

import '../../Util/HttpGo.dart';
import '../Home/Home.dart';
import 'DialogChooseInterest.dart';
import 'GroupClassFirst.dart';

class GroupClass extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _GroupClass();
  }
}

class _GroupClass extends State<GroupClass> {
  int status = 0;

  @override
  void initState() {
    getData();
    super.initState();
  }

  showChooseInterest() {
    showScaffoldDialog(context, DialogChooseInterest(() {
      getData();
    }));
  }

  dynamic data;

  getData() {
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
      HttpGo(context).get("/GroupLesson/LoadGroupLessonIndex", {}, (data) {
        status = data["status"];
        this.data = data;
        setState(() {});
        if (status == 2) {
          showChooseInterest();
        }
      }, (code, error) => showToast(error));
    });
  }

  ///status：6，進入教室
  joinClassRoom() {
    PageUtil().launchURL(data["enterClassroomUrl"]); //進入教室
  }

  ///status：5，取消課程
  cancelLesson() {
    int timestamp = DateTime.now().millisecondsSinceEpoch ~/ 1000;
    showWidgetDialog(context, DialogCancelClass(onConfirm: () {
      HttpGo(context).post("/GroupLesson/CancelReserveGroupLessonClass", {"DateTimeStamp": timestamp}, (data) {
        Home.homeKey.currentState?.getHomePage(true);
        getData();
      }, (code, error) => showToast(error));
    }));
  }

  ///status：3，預定課程（我要上課）
  wantLesson() {
    int timestamp = DateTime.now().millisecondsSinceEpoch ~/ 1000;
    HttpGo(context).post("/GroupLesson/ReserveGroupLesson", {"DateTimeStamp": timestamp}, (data) {
      getData();
    }, (code, error) => showToast(error));
  }

  @override
  Widget build(BuildContext context) {
    print("build=========");
    Widget body = Container();
    String title = "月費團課";
    String msg = "";
    if (status == 1) {
      body = GroupClassFirst(data["buyPageItem"], onFinish: () {
        getData();
      });
      title = "月費團課 - 初次購買";
    }
    if (status >= 3) {
      DateTime begin = DateTime.fromMillisecondsSinceEpoch(data["beginTimeStamp"] * 1000);
      DateTime end = DateTime.fromMillisecondsSinceEpoch(data["endTimeStamp"] * 1000);
      String time = getStrTime(begin, DateUtil.HM) + " - " + getStrTime(end, DateUtil.HM);
      msg = data["message"] ?? "";
      body = Column(children: [
        Container(
            margin: EdgeInsets.fromLTRB(16, 16, 16, 24),
            padding: EdgeInsets.fromLTRB(16, 16, 16, 16),
            decoration: Global.getWhiteBg_shadow(8, MyColor.DD),
            child: Column(mainAxisSize: MainAxisSize.min, children: [
              Row(mainAxisAlignment: MainAxisAlignment.center, children: [
                LocalImage("time_blue.png", height: 18, width: 32),
                Text("$time", style: TextStyle(fontSize: 15, color: MyColor.Green, fontWeight: FontWeight.bold))
              ]),
              Container(height: 0.8, color: MyColor.Green, margin: EdgeInsets.only(top: 8, bottom: 16)),
              Text("$msg", textAlign: TextAlign.center, style: TextStyle(fontSize: 16, color: MyColor.Green, fontWeight: FontWeight.bold)),
              Container(height: 12),
              Visibility(visible: status == 6, child: Button("進入教室", height: 32, radius: 4, bgColor: MyColor.Orange, onTap: joinClassRoom)),
              Visibility(
                  visible: status == 5,
                  child: Button("取消課程", height: 32, radius: 4, bgColor: MyColor.Orange, isBorderBg: true, onTap: cancelLesson)),
              Visibility(visible: status == 3, child: Button("我要上課", height: 32, radius: 4, bgColor: MyColor.Green, onTap: wantLesson))
            ]))
      ]);
    }
    return MyBgPage(title, body, bg2: true);
  }
}

class DialogCancelClass extends StatelessWidget {
  Function() onConfirm;

  DialogCancelClass({required this.onConfirm});

  @override
  Widget build(BuildContext context) {
    return Container(
        padding: EdgeInsets.fromLTRB(16, 16, 16, 16),
        decoration: Global.getWhiteBg(8),
        child: Column(mainAxisSize: MainAxisSize.min, children: [
          Text("取消課程", style: TextStyle(fontSize: 15, color: MyColor.Green, fontWeight: FontWeight.bold)),
          Container(height: 0.8, color: MyColor.Green, margin: EdgeInsets.only(top: 8, bottom: 16)),
          Text("親愛的學員，您確定要取消此堂課嗎？"),
          Container(height: 16),
          Row(children: [
            Expanded(
                child: Button("取消", height: 32, radius: 4, bgColor: MyColor.Green, isBorderBg: true, onTap: () {
              PageUtil().back(context);
            })),
            Container(width: 16),
            Expanded(
                child: Button("確定", height: 32, radius: 4, bgColor: MyColor.Green, onTap: () {
              onConfirm.call();
              PageUtil().back(context);
            }))
          ]),
        ]));
  }
}
